package com.edu.buservice.dal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.buservice.dal.mapper.SysPermissionsMapper;
import com.edu.buservice.dal.model.SysPermissions;
import com.edu.buservice.dal.model.SysRolePermissions;
import com.edu.buservice.dal.model.SysRoles;
import com.edu.buservice.dal.service.SysPermissionsService;
import com.edu.buservice.dal.service.SysRolePermissionsService;
import com.edu.buservice.dal.service.SysRolesService;
import com.edu.buservice.util.model.enums.ErrorCodeEnum;
import com.edu.buservice.util.model.error.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author 86177
 * @description 针对表【sys_permissions(原子权限表)】的数据库操作Service实现
 * @createDate 2025-02-05 23:31:46
 */
@Service
@Slf4j
public class SysPermissionsServiceImpl extends ServiceImpl<SysPermissionsMapper, SysPermissions>
		implements SysPermissionsService{

	@Autowired
	private SysRolesService sysRolesService;

	@Autowired
	private SysRolePermissionsService sysRolePermissionsService;

	@Override
	public List<SysPermissions> getPermissionsByRoleId(Integer roleId) {
		// 输入验证
		if (roleId == null) {
			throw new IllegalArgumentException("roleId 不能为空");
		}

		try {
			// 获取角色信息
			LambdaQueryWrapper<SysRoles> rolesQueryWrapper = new LambdaQueryWrapper<>();
			rolesQueryWrapper.eq(SysRoles::getId, roleId);
			rolesQueryWrapper.eq(SysRoles::getDeleted, 0);
			SysRoles sysRoles = sysRolesService.getOne(rolesQueryWrapper);

			if (sysRoles == null) {
				return Collections.emptyList(); // 或者抛出自定义异常
			}

			// 获取角色权限信息
			LambdaQueryWrapper<SysRolePermissions> rolePermissionsQueryWrapper = new LambdaQueryWrapper<>();
			rolePermissionsQueryWrapper.eq(SysRolePermissions::getRoleId, sysRoles.getId());
			rolePermissionsQueryWrapper.eq(SysRolePermissions::getDeleted, 0);
			SysRolePermissions sysRolePermissions = sysRolePermissionsService.getOne(rolePermissionsQueryWrapper);

			if(sysRolePermissions == null){
				return Collections.emptyList();
			}

			// 获取权限码
			List<Integer> permissionIds = Arrays.stream(sysRolePermissions.getPermissionId().split(","))
					.map(Integer::parseInt).toList();

			return listByIds(permissionIds);

		} catch (Exception e) {
			// 记录日志并抛出自定义异常
			log.error("获取权限信息失败", e);
			throw new BizException(ErrorCodeEnum.DATABASE_ERROR);
		}
	}

}




